import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createCategory, deleteCategory, updateCategory } from './categoryMutations'
import { toast } from 'sonner'
import { CategorySchema } from '../_types/categorySchema'

const useDeleteCategory = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (id: number) => {
      await deleteCategory(id)
    },
    onSuccess: () => {
      toast.success('删除成功')
      queryClient.invalidateQueries({
        queryKey: ['categories']
      })
    }
  })
}

const useCreateCategory = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (category: CategorySchema) => {
      await createCategory(category)
    },
    onSuccess: () => {
      toast.success('创建成功')
      queryClient.invalidateQueries({
        queryKey: ['categories']
      })
    },
    onError: error => {
      console.log('%c [ error ]-36', 'font-size:13px; background:pink; color:#bf2c9f;', error)
      toast.error(error.message)
    }
  })
}
const useUpdateCategory = () => {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: async (category: CategorySchema) => {
      await updateCategory(category)
    },
    onSuccess: () => {
      toast.success('修改成功')
      queryClient.invalidateQueries({
        queryKey: ['categories']
      })
    },
    onError: error => {
      toast.error(error.message)
    }
  })
}

export { useDeleteCategory, useCreateCategory, useUpdateCategory }
